//
//  ZSViewController.m
//  intelligent
//
//  Created by 甘世清 on 2024/3/27.
//

#import "ZSViewController.h"
#import "ZSCollectionViewCell.h"
#import <RMStore/RMStore.h>
#import "VModel.h"
@interface ZSViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic , strong) VModel * vModel;

@end

@implementation ZSViewController
- (void)dealloc{
    DTLog(@"购买页是否释放");
    [YJProgressHUD hide];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self zx_setRightBtnWithText:SQNSLocalString(@"恢复购买") clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        [YJProgressHUD SQ_showMsgWithoutView:@""];
       [[RMStore defaultStore] restoreTransactionsOnSuccess:^(NSArray *transactions) {
             [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"没有购买可以恢复")];
        } failure:^(NSError *error) {
            [YJProgressHUD showMsgWithoutView:SQNSLocalString(@"暂无数据")];
        }];
    }];
    self.zx_navBar.zx_rightBtn.zx_fixWidth = 60;
     self.zx_navBar.zx_rightBtn.zx_fixImageSize = CGSizeMake(0, 0);
    self.zx_navBar.zx_rightBtn.titleLabel.font = FONT_MEDIUM(12);
 }
- (void)SQ_UIViewForSelfView{
    
    UIScrollView * scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
    scrollView.contentSize = CGSizeMake(SCREEN_WIDETH, 800);
    scrollView.showsVerticalScrollIndicator = FALSE;
    [self.view addSubview:scrollView];
    scrollView.backgroundColor =  UIColor.clearColor;
    
    UIView * bgView = [[UIView alloc]init];
    bgView.backgroundColor =  UIColor.clearColor;
    [scrollView addSubview:bgView];
     [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.left.top.equalTo(scrollView);
         make.width.mas_equalTo(SCREEN_WIDETH);
         make.height.mas_equalTo(790);
    }];
    
    
    UIImageView * bgImage = [[UIImageView alloc]init];
    bgImage.image = SQGetImage(@"背景");
    bgImage.clipsToBounds = YES;
    bgImage.contentMode = UIViewContentModeScaleAspectFill;
    [bgView addSubview:bgImage];
    [bgImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(bgView);
        make.height.mas_equalTo(SCREEN_WIDETH*184/375);
    }];
    
    UIImageView * image1 = [[UIImageView alloc]init];
    image1.image = SQGetImage(@"积分");
    image1.clipsToBounds = YES;
    image1.contentMode = UIViewContentModeScaleAspectFit;
    [bgView addSubview:image1];
    [image1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(222);
        make.centerX.equalTo(bgView);
        make.top.equalTo(bgView).offset(22);
    }];
    
    UIImageView * image2 = [[UIImageView alloc]init];
    image2.image = SQGetImage(@"升级进阶智能版本 1");
    image2.clipsToBounds = YES;
    image2.contentMode = UIViewContentModeScaleAspectFit;
    [bgView addSubview:image2];
    [image2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(image1);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(180);
        make.bottom.equalTo(image1.mas_bottom).offset(-10);
    }];
    NSArray * array = @[@"高清图片制作 · 一句话直接出图",@"最新AI作图模型 · 享受最新作图技术"];
    NSArray * array2 = @[@"简单直接，无需复杂提示词",@"让AI激发艺术创造力"];
    for (int x= 0; x<array.count; x++) {
        UIImageView * left = [[UIImageView alloc]init];
        left.image = SQGetImage(@"编组");
        [bgView addSubview:left];
        [left mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(bgView).offset(60);
            make.size.mas_equalTo(20);
            make.top.equalTo(image1.mas_bottom).offset(15+x*64);
        }];
        UILabel * label1 = [[UILabel alloc]init];
        label1.text = SQNSLocalString([array objectAtIndex:x]);
        label1.font = FONT_REGULAR(14);
        label1.textColor = SQColor333333;
        [bgView addSubview:label1];
        [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(left);
            make.left.equalTo(left.mas_right).offset(8);
            make.height.mas_equalTo(22);
        }];
        UILabel * label2 = [[UILabel alloc]init];
        label2.text = SQNSLocalString([array2 objectAtIndex:x]);
        label2.font = FONT_SEMIBOLD(14);
        label2.textColor = SQColor333333;
        [bgView addSubview:label2];
        [label2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(label1.mas_bottom).offset(3);
            make.left.equalTo(left.mas_right).offset(8);
            make.height.mas_equalTo(22);
        }];
    }
  
    [self.collectionView registerClass:[ZSCollectionViewCell class] forCellWithReuseIdentifier:@"ZSCollectionViewCell"];
    self.collectionView.alwaysBounceVertical = NO;
    UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView.collectionViewLayout = flowLayout;
    [bgView addSubview:self.collectionView];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(bgView);
        make.top.equalTo(image1.mas_bottom).offset(160);
        make.height.mas_equalTo(150);
    }];
    
    HeaderView * btn = [[HeaderView alloc]init];
    btn.font = FONT_SEMIBOLD(16);
    btn.text = SQNSLocalString(@"充值积分");
    btn.colorString =  @"#000000";
    btn.layer.cornerRadius = 6;
    btn.backgroundColor = SQColor(@"#4AF8CE");
    [btn.btn addTarget:self action:@selector(SQ_buttonClick) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).offset(32);
        make.height.mas_equalTo(48);
        make.width.mas_equalTo(SCREEN_WIDETH-44);
        make.centerX.equalTo(bgView);
    }];
    
    NSArray * buttonArray = @[@"用户协议",@"隐私协议"];
    for (int x = 0; x< buttonArray.count; x++) {
        UIButton * btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn1 setTitle:SQNSLocalString([buttonArray objectAtIndex:x]) forState:normal];
        [btn1 setTitleColor:SQColor333333 forState:normal];
        btn1.titleLabel.font = FONT_MEDIUM(12);
        [btn1 addTarget:self action:@selector(SQ_ThreeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        btn1.tag = 1000+x;
        [bgView addSubview:btn1];
        [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(SCREEN_WIDETH/2.f);
            make.height.mas_equalTo(40);
            make.left.equalTo(bgView).offset(x*(SCREEN_WIDETH/2.f));
            make.top.equalTo(btn.mas_bottom).offset(25);
        }];
        UIView * lineView = [[UIView alloc]init];
        lineView.backgroundColor = SQColor333333;
        [bgView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(50);
            make.height.mas_equalTo(1);
            make.centerX.equalTo(btn1);
            make.bottom.equalTo(btn1.mas_bottom).offset(-12);
        }];
    }

    [self SQ_Header];
}
- (void)SQ_Header{
    [self.jsonArray removeAllObjects];
    [HttpTool post:@"diamondRecharge/list" paramDic:[NSMutableDictionary new] successBlock:^(BaseModel * _Nonnull httpModel) {
        NSArray * array = [VModel mj_objectArrayWithKeyValuesArray:httpModel.data];
        [self.jsonArray addObjectsFromArray:array];
        if (array.count >0) {
            self.vModel = array.firstObject;
            self.vModel.isseleted = YES;
        }
        [self SQ_RMStore];
        [self.collectionView reloadData];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
  
}
-(void)SQ_RMStore{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSMutableArray * array = [[NSMutableArray alloc]init];
    [self.jsonArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        VModel * model = (VModel*)obj;
        [array addObject:model.appleId];
    }];
     [[RMStore defaultStore] requestProducts:[NSSet setWithArray:array] success:^(NSArray *products, NSArray *invalidProductIdentifiers) {
         [YJProgressHUD hide];
        if([products count] == 0){
            DTLog(@"--------------没有商品------------------");
            return;
        }
        DTLog(@"内购商品列表------%@",products);
    } failure:^(NSError *error) {
        [YJProgressHUD hide];
        DTLog(@"--------------请求商品失败--------------%@----",error);
    }];
}
 
-(void)SQ_buttonClick{
    //调用内购
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    WS(weakSelf);
     [[RMStore defaultStore] addPayment:self.vModel.appleId success:^(SKPaymentTransaction *transaction) {
            [weakSelf checkIAPResultWithtransactionReceiptblock];
        } failure:^(SKPaymentTransaction *transaction, NSError *error) {
            [YJProgressHUD showMsgWithoutView: SQNSLocalString(@"交易失败")];
    }];
}
- (void)checkIAPResultWithtransactionReceiptblock
{
    [YJProgressHUD SQ_showMsgWithoutView:@""];
    NSURL *receiptURL = [[NSBundle mainBundle] appStoreReceiptURL];
        if (receiptURL) {
            NSData *receiptData = [NSData dataWithContentsOfURL:receiptURL];
            
            NSString *encodeStr = [receiptData base64EncodedStringWithOptions: NSDataBase64EncodingEndLineWithLineFeed];
             NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
            [dic setObject:encodeStr forKey:@"certificate"];
             [YJProgressHUD SQ_showMsgWithoutView:@""];
            [HttpTool post:@"diamondRecharge/recharge"  paramDic:dic successBlock:^(BaseModel * _Nullable httpModel) {
                
                for (SKPaymentTransaction *aTransaction in [[SKPaymentQueue defaultQueue] transactions]) {
                    [[SKPaymentQueue defaultQueue]finishTransaction:aTransaction];
                }
                //更新用户信息
                [self SQ_userInfo];
                [self SQ_showChenggong];
            } andFailBloc:^(BaseModel * _Nullable httpModel, NSError * _Nullable error) {
                [YJProgressHUD showMsgWithoutView:httpModel.message];
            }];
        }else{
            [YJProgressHUD hide];
        }
}

- (void)SQ_userInfo{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    [HttpTool post:@"user/info" paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        UserModel * mo = [UserModel share];
        UserModel* model = [UserModel mj_objectWithKeyValues:httpModel.data];
        model.token = mo.token;
        [UserModel updateLocalUserModel:model];
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}

-(void)SQ_showChenggong{
    SQCustomButton * view = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(32, 32) midmargin:12];
    view.frame = CGRectMake(0, 0, 200, 120);
    view.text = SQNSLocalString(@"制图积分充值成功");
    view.layer.cornerRadius = 8;
    view.layer.masksToBounds = YES;
    view.backgroundColor = UIColor.whiteColor;
    view.font = FONT_REGULAR(16);
    view.image = SQGetImage(@"选中头像");
    LSTPopView * pop = [LSTPopView initWithCustomView:view
                                           parentView:nil
                                             popStyle:LSTPopStyleSmoothFromBottom dismissStyle:LSTDismissStyleSmoothToBottom];
    pop.hemStyle = LSTHemStyleCenter;
    pop.showTime = 2;
    [pop pop];
}

-(void)SQ_ThreeButtonClick:(UIButton*)btn{
    if (btn.tag == 1000) {
        CommonWebVcView *vc= [[CommonWebVcView alloc]init];
        vc.urlStr =  @"https://chatai.funlovemore.top/#/agreementInfo?id=1";
        [self.navigationController pushViewController:vc animated:YES];
    } else if (btn.tag == 1001) {
        CommonWebVcView *vc= [[CommonWebVcView alloc]init];
        vc.urlStr =  @"https://chatai.funlovemore.top/#/agreementInfo?id=2";
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.jsonArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    ZSCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZSCollectionViewCell" forIndexPath:indexPath];
    cell.model = [self.jsonArray objectAtIndex:indexPath.item];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    return CGSizeMake(100, 140);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 12;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 12, 0, 12);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.vModel.isseleted = NO;
    self.vModel = [self.jsonArray objectAtIndex:indexPath.item];
    self.vModel.isseleted = YES;
    [self.collectionView reloadData];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

}


@end
